import { Component, OnInit, ViewChild } from '@angular/core';
import { NzModalService, NzMessageService } from 'ng-zorro-antd';
import { Utils, Lang, Status } from '../../../common/helper/util-helper';
import { delay } from 'rxjs/operators';
import { RoleService } from '../../../services/organization/Role/role.service';
import { Router, ActivatedRoute, Params } from '@angular/router';

@Component({
  selector: 'app-role',
  templateUrl: './role.component.html',
  styleUrls: ['./role.component.scss']
})
export class RoleComponent implements OnInit {


  public status = {
    // 权限隐藏入口
    sc: '3870c648-4aea-4b85-ba3f-f2f63b96136a',
    // 列表数据集合
    dataList: [],
    // 模态框按钮提交状态
    isConfirmLoading: false,
    // 批量删除按钮状态
    delBtnStatus: false,
    // 全选状态
    allChecked: false,
    // 半选状态
    indeterminate: false,
    // 当前选中的数据集合
    checkedDatas: [],
    // 当前选中节点
    activedNode: null,
    // 关键词搜索
    filter: '',
    // 待编辑节点
    editNode: null,
    // 编辑
    isedit: false,
    // 新增部门模态框状态
    isadd: false,
    // 删除部门模态框
    isDelete: false,
    // 角色名
    title: null,
    // 角色描述
    description: null,
    // 保存按钮状态动画
    isOkLoading: false,
    // 分页相关数据集合对象
    pager: {
      // 当前页
      pageIndex: 1,
      // 总记录数
      totalCount: 1,
      // 每页显示记录数
      pageSize: 10,
      // 总页数
      totalPages: 1
    },
    // 权限数据
    authority: [],
    // 默认权限无法修改
    cantModify: false,
    ChoosedRoleAuthority: null,
    // 需要显示的权限菜单列表
    authorityObjs: {
      'APJ.System': true,
      'APJ.Project': true,
      'APJ.Organizations_DocumentLibrarys': true
    },
    // // 当前页面所需要的权限
    // pagePermissions: [
    //   'APJ.System.Role'
    // ],
    // // 当前页面权限
    // pageAuthorty: {
    //   // Role: null
    // },

  };



  /**
       * 初始化数据
       */
  protected async init() {

    this.status.allChecked = false;
    this.status.indeterminate = false;
    this.status.checkedDatas = [];
    if (this.status.checkedDatas.length == 0) {
      this.status.delBtnStatus = true;
    }
    const pramas = {
      // 每页记录数
      maxResultCount: this.status.pager.pageSize,
      // 当前页数
      SkipCount: this.status.pager.pageIndex - 1,
      // 关键词搜索
      filter: this.status.filter,
    };
    // 获取角色列表
    this.roleService.GetRoles(pramas).then((res) => {
      // console.log(res);
      if (res.success) {
        this.status.pager.totalCount = res.result.totalCount;
        this.status.pager.totalPages = res.result.totalCount;
        this.status.dataList = res.result.items;
      } else {
        this.message.warning(res.error.message);
      }
    });
    // 获取权限列表
    this.roleService.GetRoleForEdit().then((res) => {
      // console.log(res);
      if (res.success) {
        // 保存权限集合
        const permissions = res.result.permissions;
        // 保存当前角色拥有的权限
        const grantedPermissionNames = res.result.grantedPermissionNames;
        // 处理权限数据
        this.disposePermissionsData(permissions, grantedPermissionNames);
      } else {
        this.message.warning(res.error.message);
      }
    });

  }

  /**************************************************权限数据处理***************************************************** */

  /**
     * 处理权限数据 生成权限点
     * @param permissions 权限数据
     */
  private disposePermissionsData(permissions, grantedPermissionNames) {
    // console.log(permissions);

    // 获取首级
    const tempPermission = {};
    const authorityObjs = this.status.authorityObjs;
    // 总权限数据
    Utils.resetData(permissions, (permission) => {
      const permissionKey = permission.name;
      // 匹配权限关键字
      // 如果能在authorityObjs 找到该权限
      if (authorityObjs[permissionKey]) {
        tempPermission[permissionKey] = tempPermission[permissionKey] || {
          text: null,
          key: null,
          group: []
        };
        tempPermission[permissionKey].text = permission.displayName;
        tempPermission[permissionKey].key = permissionKey;
      } else {
        for (const key in authorityObjs) {
          if (permissionKey.indexOf(key) > -1) {
            // 权限组集合
            let groupItem = tempPermission[key];
            if (!groupItem) {
              groupItem = { text: null, key: null, group: [] };
              tempPermission[key] = groupItem;
            }
            groupItem.group = groupItem.group || [];
            let checkStatus = false;
            Utils.resetData(grantedPermissionNames, (nameItem) => {
              if (permissionKey == nameItem) {
                checkStatus = true;
                return 'break';
              }
            });
            groupItem.group.push({
              value: permissionKey,
              label: permission.displayName,
              key: permissionKey,
              checked: checkStatus
            });
          }
        }
      }
    });
    // 重新排序Permissions
    // 排序后的新数组
    let reOrderPermissions = [];
    for (let key in tempPermission) {
      // console.log(tempPermission[key])
      if (key === 'APJ.System') {
        reOrderPermissions[0] = tempPermission[key]
      } else if (key === 'APJ.Project') {
        reOrderPermissions[1] = tempPermission[key]
      } else if (key === 'APJ.Organizations_DocumentLibrarys') {
        reOrderPermissions[2] = tempPermission[key]
      }

    }
    // 保存排序后的权限数组
    this.status.authority = reOrderPermissions;
    // console.log(this.status.authority)

  }

  /**
     * 添加或编辑时，获取当前选中的角色权限
     */
  private getChoosedRoleAuthority() {
    const resultAuthority = [];
    // tslint:disable-next-line: no-eval
    const grantedPermissions = eval(
      '(' + Utils.getLocalStorage(Status.grantedPermissions) + ')'
    );
    // 除设置的权限外，其他权限全部加入
    // tslint:disable-next-line: forin
    for (const key in grantedPermissions) {
      let keyStatus = true;
      for (const authorityKey in this.status.authorityObjs) {
        // tslint:disable-next-line: triple-equals
        if (key.indexOf(authorityKey) != -1) {
          keyStatus = false;
        }
      }
      if (keyStatus) {
        resultAuthority.push(key);
      }
    }
    // tslint:disable-next-line: prefer-const
    // tslint:disable-next-line: forin
    for (const authorityKey in this.status.authorityObjs) {
      resultAuthority.push(authorityKey);
    }

    // 获取当前设置的属性
    const authority = this.status.authority;
    let i = 0,
      len = authority.length,
      authorityItem;
    for (; i < len; i++) {
      authorityItem = authority[i];
      const group = authorityItem.group;
      let j = 0,
        lenJ = group.length,
        groupItem;
      for (; j < lenJ; j++) {
        groupItem = group[j];
        if (groupItem.checked) {
          resultAuthority.push(groupItem.key);
          // 还原状态
          // groupItem.checked = false;
        }
      }
    }
    // console.log(resultAuthority);
    return resultAuthority;
  }


  /**
   * 清空权限
   */
  private clearRoleAuthority() {
    let authority = this.status.authority;
    Utils.resetData(authority, (authorityItem) => {
      let group = authorityItem.group;
      Utils.resetData(group, (groupItem) => {
        groupItem.checked = false;
      });
    });
  }
  /**************************************************权限数据处理结束*************************************************** */




  // 选中相关************************************************************************************************************
  /**
     * 全部选中
     * @param status <any> 全选框的选中状态
     */
  public checkAll(status: any, callBack?: Function) {
    this.status.dataList.forEach((data: any) => {
      let eachStatus;
      if (callBack) {
        eachStatus = callBack(data);
      }
      if (eachStatus !== false) {
        data['checked'] = status;
      }
    });
    this.refreshCheckboxStatus();
  }

  /**
   * 刷新(所有复选框)状态
   */
  private refreshCheckboxStatus() {
    const dataList = this.status.dataList;
    const allChecked = dataList.filter((value: any) => !value['disabled']).every((value: any) => value['checked'] === true);
    const allUnChecked = dataList.filter((value: any) => !value['disabled']).every((value: any) => !value['checked']);

    this.status.allChecked = allChecked;
    this.status.indeterminate = (!allChecked) && (!allUnChecked);

    // 获取当前选中的数据
    const checkedDatas = [];
    dataList.forEach((data) => {
      if (data['checked']) {
        checkedDatas.push(data);
      }
    });
    this.status.checkedDatas = checkedDatas;
    // 改变批量操作按钮状态
    this.status.delBtnStatus = !dataList.some((value: any) => value['checked']);
  }

  /**
   * 获取当前选中项
   */
  public getCheckedData() {
    return this.status.checkedDatas;
  }
  // 选中相关结束********************************************************************************************************





  // 新增角色
  addRole() {
    this.status.isadd = true;

  }
  addSave() {
    if (!this.status.title) {
      this.message.warning('名称不能为空');
    } else if (!this.status.description) {
      this.message.warning('描述不能为空');
    } else {
      // 获取基础权限及选择的权限
      this.status.ChoosedRoleAuthority = this.getChoosedRoleAuthority()
      const params = {
        role: {
          // id: this.status.editNode.id,
          displayName: this.status.title,
          description: this.status.description,
          isDefault: false,
        },
        grantedPermissionNames: this.status.ChoosedRoleAuthority
      };
      this.status.isOkLoading = true;
      this.roleService.CreateOrUpdateRole(params).then((res) => {
        // console.log(res)
        if (res.success) {
          this.status.isadd = false;
          this.message.success('添加成功');
          this.init();
        } else {
          this.status.isadd = false;
          this.message.warning(res.error.message);
        }
        // 关闭输入框并清空输入框值
        // this.status.isadd = false;
        this.status.isOkLoading = false;
        this.status.title = null;
        this.status.description = null;
      });
    }

  }

  // 编辑角色
  protected editRole(node) {
    console.log(node);
    // 权限隐藏 入口
    let type = this.routeInfo.queryParams;
    if (type['value'].sc == this.status.sc) {
      this.status.cantModify = false;
      console.log(11)
      // console.log(type['value'].sc)
    } else {
      // this.status.cantModify = true;
      if (node.name === 'Admin') {
        this.status.cantModify = true;
      } else if (node.name === 'Project') {
        this.status.cantModify = true;
      } else if (node.name === 'BranchCompany') {
        this.status.cantModify = true;
      } else if (node.name === 'Normal') {
        this.status.cantModify = true;
      } else {
        this.status.cantModify = false;
      }
    }


    this.status.isedit = true;
    this.status.editNode = node;
    this.status.title = this.status.editNode.displayName;
    this.status.description = this.status.editNode.description;


    // 获取当前编辑角色的权限点
    // 获取权限列表
    const params = {
      id: node.id
    };
    this.roleService.GetRoleForEdit(params).then((res) => {
      console.log(res);
      if (res.success) {
        // 保存权限集合
        const permissions = res.result.permissions;
        // 保存当前角色拥有的权限
        const grantedPermissionNames = res.result.grantedPermissionNames;
        // 处理权限数据
        this.disposePermissionsData(permissions, grantedPermissionNames);
      } else {
        this.message.warning(res.error.message);
      }
    });
  }

  // 确定修改角色
  async editSave() {
    // 获取基础权限及选择的权限
    this.status.ChoosedRoleAuthority = this.getChoosedRoleAuthority()
    const params = {
      role: {
        id: this.status.editNode.id,
        displayName: this.status.title,
        description: this.status.description,
        isDefault: false,
      },
      grantedPermissionNames: this.status.ChoosedRoleAuthority
    };
    this.status.isOkLoading = true;
    await this.roleService.CreateOrUpdateRole(params).then((res) => {
      if (res.success) {
        // this.message.success('修改成功');
        this.message.warning('修改成功，该角色下的账号需重新登录后方可生效')
        this.init();
      } else {
        this.message.warning(res.error.message);
      }
      // 关闭输入框并清空输入框值
      this.clearRoleAuthority();
      this.status.cantModify = false;
      this.status.isedit = false;
      this.status.isOkLoading = false;
      this.status.title = null;
      this.status.description = null;
    });

  }


  // 删除角色
  protected delRole(node) {
    // this.status.isDelete = true;
    this.status.editNode = node;
    // console.log(node)
    this.status.title = this.status.editNode.displayName;
    this.mzModal.error({
      nzTitle: '删除组织',
      nzContent: '<p>删除后不能恢复，请谨慎操作。</p>',
      nzOnOk: () => this.delNode(),
      nzOkText: '确定',
      nzOkType: 'danger',
      nzCancelText: '取消',
      nzOnCancel: () => { }
    });
  }
  // 确定删除角色
  delNode() {
    const params = {
      id: this.status.editNode.id
    };
    // console.log(params)
    this.roleService.DeleteRole(params).then((res) => {
      if (res.success) {
        this.message.success('删除成功');
        this.init();
      } else {
        this.message.error(Utils.errorMessageProcessor(res, Lang.deleteFail));
      }
      this.status.isDelete = false;
      this.status.editNode = null;
      this.status.activedNode = null;
      this.status.title = null;
      this.status.description = null;
    });
  }
  // 取消删除
  Canceldel() {
    this.status.isDelete = false;
    this.status.editNode = null;
    this.status.activedNode = null;
    this.status.title = null;
    this.status.description = null;
  }


  // 批量删除人员？
  public delmembers() {
    this.mzModal.error({
      nzTitle: '批量删除',
      nzContent: '<p>确认要批量删除吗？删除后无法恢复</p>',
      nzOnOk: () => this.delRoles(),
      nzOkText: '确定',
      nzOkType: 'danger',
      nzCancelText: '取消',
      nzOnCancel: () => { }
    });
  }
  // 批量删除角色
  delRoles() {
    let params = []
    this.getCheckedData().forEach((item) => {
      params.push(item.id);
    });
    console.log(params);
    if (params) {
      this.roleService.BatchDeleteRole(params).then((res) => {
        if (res.success) {
          this.message.success('删除成功');
        } else {
          this.message.warning(res.error.message);
        }
        // 重新加载
        this.init()
      })
    }
  }

  // 取消编辑或添加
  cancelAddOredit() {
    this.clearRoleAuthority();
    this.status.cantModify = false;
    this.status.isDelete = false;
    this.status.editNode = null;
    this.status.isedit = false;
    this.status.isadd = false;
    this.status.isOkLoading = false;
    this.status.title = null;
    this.status.description = null;
    // this.status.ChoosedRoleAuthority = null;
    console.log('数据已清除');
  }


  /*分页相关******************************************************************************** */
  /**
  * 刷新列表
  */
  public refreshDataList() {
    const refresh = this['init'].bind(this);
    if (refresh) {
      refresh();
    }
  }

  /**
   * 列表分页
   * @param index <number> 非必填，列表跳转至第几页，默认为当前页(即刷新当前页数据)
   */
  public pageIndexChange(index?: any) {

    const pager = this.status.pager;
    pager.pageIndex = index || pager.pageIndex;
    this.refreshDataList();
  }

  /**
   * 改变每页记录条数
   * @param size <number> 非必填
   */
  public pageSizeChange(size?: number) {
    const pager = this.status.pager;
    pager.pageSize = size || pager.pageSize;
    this.pageIndexChange();
  }
  /**********************************************************************************分页相关结束 */

  /**
   * 关键字搜索
   */
  public searchEvent() {
    // 搜索时重置分页
    this.status.pager.pageIndex = 1;
    this.init();
  }

  /**
   * 搜索框回车事件
   * @param e <Event>
   */
  public keyupEvent(e: Event) {
    Utils.enter(e, this.searchEvent.bind(this));
  }


  constructor(private roleService: RoleService,
    public message: NzMessageService,
    public mzModal: NzModalService,
    private routeInfo: ActivatedRoute, ) { }

  ngOnInit() {
    this.init();
    // 重置选中框状态
    this.status.delBtnStatus = !this.status.dataList.some((value: any) => value['checked']);

  }

}
